#include <stdio.h>
#include <stdlib.h>
#include "vc1dec_api.h"

unsigned char input[1024*1024];

void writeOutput(FILE* fp,unsigned char* Y, unsigned char* U,unsigned char* V,int width,int height,int stride)
{
	int i = 0;
	for(i = 0; i < height; i++)
	{
		fwrite(Y,1,width,fp);
		Y += stride;
	}

	for(i = 0; i < height/2; i++)
	{
		fwrite(U,1,width/2,fp);
		U += (stride/2);
	}

	for(i = 0; i < height/2; i++)
	{
		fwrite(V,1,width/2,fp);
		V += (stride/2);
	}
}

int readFrameData(FILE* fp,unsigned char* framedata)
{
	//////
	unsigned int element = 0;
	int size = 0;
	unsigned int timestamp = 0;
	int len = 0;
	
	size = fread(&element,4,1,fp);
	if(size != 1)////foe
	{
		printf("foe\n");
		return 0;
	}

	len = element & 0x00ffffff;

	size = fread(&timestamp,4,1,fp);
	if(size != 1)
	{
		printf("foe\n");
		return 0;
	}

	size = fread(framedata,1,len,fp);
	if(size != len)
	{
		printf("foe\n");
		return 0;
	}

	return len;

}
int main(int argc,char** argv)
{
	unsigned int  temp;
	char *inputfile, *outputfile;
	FILE *pIn, *pOut;
	int width,height;
	char profile,level=0;
	VC1DECODER decoder;
	HRESULT_VC1 rt = VC1_OK;
	if(argc != 3)
	{
		printf("usage: decoder inputfile outputfile\n");
		return -1;
	}

	inputfile = argv[1];
	outputfile = argv[2];

	pIn = fopen(inputfile,"rb");
	if(!pIn)
	{
		printf("invalid input file %s\n",inputfile);
		return -1;
	}

	pOut = fopen(outputfile,"wb");
	if(!pOut)
	{
		printf("invalid output file %s\n",outputfile);
		return -1;
	}

	fread(&temp,1,4,pIn);
	if((temp >> 24) != 0xc5)
	{
		printf("invalid rcv input file\n");
		return -1;
	}

	fread(&temp,1,4,pIn);///must be 4
	if(temp != 4)
	{
		printf("invalid rcv input file\n");
		return -1;
	}

	fread(input,1,4,pIn);///struct c
	profile = input[0] >> 4;////

	///get height
	fread(&height,1,4,pIn);

	///get width
	fread(&width,1,4,pIn);

	fread(&temp,1,4,pIn);
	if(temp != 0xc)
	{
		printf("invalid rcv input file\n");
		return -1;
	}

	//fread(&temp,1,1,pIn);
	//level = temp >> 5;
	fseek(pIn,temp,SEEK_CUR);///skip the rest bytes
	
	rt = VC1Dec_Init(&decoder,width,height,profile,level,input,4);

	if(VC1_OK != rt)
	{
		printf("failed to initialize the VC1 decoder\n");
		return -1;
	}



	while(1)
	{
		int len = 0;
		if((len = readFrameData(pIn,input)) <= 0)///////
		{
			break;
		}

		if(VC1Dec_DecodeData(decoder,input,len) == VC1_OK)
		{
			unsigned char* Y,*U,*V;
			int w,h,stride;
			if(VC1_OK == VC1Dec_GetDecodedFrame(decoder,&Y,&U,&V,&w,&h,&stride))
				writeOutput(pOut,Y,U,V,w,h,stride);
		}
	}


	return 0;
}